package com.atguigu.lease.web.admin.custom.interceptor;


import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.login.LoginUser;
import com.atguigu.lease.common.login.LoginUserHolder;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @ClassName: AuthenticationInterceptor
 * @Description: 拦截器
 * @Author: yangchengbao
 * @Create: 2025/1/4 11:43
 * @Version: 1.0
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    /**
     * @param request
     * @param response
     * @param handler
     * @Desceription:
     * @Return: boolean
     * @Author: yangchengbao
     * @Date: 2025-01-04 11:01:12
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("access-token");
        //解析token
        Claims claims = JwtUtil.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginUserHolder.setLoginUser(new LoginUser(userId, username));//把用户信息放到ThreadLocal中

        return true;
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @Desceription:
     * @Return: void
     * @Author: yangchengbao
     * @Date: 2025-01-04 12:01:67
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}
